package com.think.oauth.user.security.token;

import java.io.IOException;
import java.util.Map;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.OAuth2RequestFactory;
import org.springframework.security.oauth2.provider.TokenRequest;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;

import com.think.common.model.CustomUser;
import com.think.oauth.user.qh.cas.CasUtils2;
import com.think.oauth.user.qh.cas.LoginUser;
import com.think.oauth.user.service.CustomUserDetailsService;

public class QHCasTicketCustomTokenGranter extends AbstractCustomTokenGranter {

	private CustomUserDetailsService userDetailsService;

	public QHCasTicketCustomTokenGranter(AuthorizationServerTokenServices tokenServices,
			ClientDetailsService clientDetailsService, OAuth2RequestFactory requestFactory, CustomUserDetailsService userDetailsService) {
		super(tokenServices, clientDetailsService, requestFactory, "cas");
		this.userDetailsService = userDetailsService;

	}

	@Override
	protected UserDetails getUserDetails(Map<String, String> parameters) {
		return null;
	}

	@Override
	protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) {
		// TODO Auto-generated method stub
		if (CasUtils2.hasTicket(tokenRequest)) {
			LoginUser loginUser;
			try {
				loginUser = CasUtils2.getLoginUser(tokenRequest);
				CustomUser userDetails = (CustomUser) this.userDetailsService.loadUserByQHCasUser(loginUser);
				OAuth2Authentication auth2Authentication = new OAuth2Authentication(
						tokenRequest.createOAuth2Request(client),
						new UsernamePasswordAuthenticationToken(userDetails, "N/A", userDetails.getAuthorities()));
				auth2Authentication.setAuthenticated(true);
				auth2Authentication.setDetails(userDetails);
				return auth2Authentication;
			} catch (IOException e) {
				// TODO Auto-generated catch block
				throw new InvalidGrantException("");
			}

		} else {
			throw new InvalidGrantException("");
		}

	}

}
